@colixsystems/widget-sdk 0.323.0 → 0.324.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,7 +91,11 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
91
 
92
92
  ## Status
93
93
 
94
- `v0.323.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+ `v0.324.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
95
+
96
+ ### What's new in 0.324.0 (contract 1.264.0)
97
+
98
+ **A widget can insert text at the caret of a `<MarkdownInput>`.** Pass `editorRef={ref}` (from `useRef(null)`) and the field fills it with `{ insertText(text) }`: an emoji picker or a snippet button calls `ref.current.insertText("🎉")` and the text lands where the user's caret was, on web and in the WebView on iOS and Android alike. Before the user has placed a caret, the text goes at the end. It returns `false` while the editor is still loading, so a widget can append to its value instead. `editable={false}` locks the field and its toolbar, for example while a post is saving, so nothing typed then is lost. Additive.
95
99
 
96
100
  ### What's new in 0.323.0 (contract 1.263.0)
97
101
 
@@ -3597,7 +3601,7 @@ import { defineWidget, validateManifest, useDatastoreQuery, Text, View } from "@
3597
3601
  - `ConfirmDialog` — the standard confirmation prompt, a preset of `Modal` and `Button`. `<ConfirmDialog visible={asking} tone="destructive" title="Delete this order?" message="This cannot be undone." confirmLabel="Delete" onCancel={() => setAsking(false)} onConfirm={removeOrder} />` asks before a delete or any other action that cannot be undone. Cancel, the close button, the backdrop, Escape and the Android back button fire `onCancel`; a promise returned from `onConfirm` keeps it busy (buttons disabled, a second press ignored) until it settles. Props: `visible`, `title`, `message`, `confirmLabel`, `cancelLabel`, `tone` (`default` | `destructive`), `busy`, `onConfirm`, `onCancel`, `closeAccessibilityLabel`, `testID`. Use it instead of building a confirmation from `Modal` yourself.
3598
3602
  - `Modal` — the standard dialog, built on `Overlay`. `<Modal visible={open} onRequestClose={() => setOpen(false)} title="Edit order" footer={<Button title="Save" onPress={save} />}>…</Modal>` draws a title, a close button, a body that scrolls when it is long and a footer action row laid out below it. Its background, corner radius, padding, scrim, shadow and title colour come from the theme's `modal` scope (Design > Components > Dialogs), so every dialog in an app matches. Props: `visible`, `onRequestClose`, `dismissible`, `title`, `footer`, `presentation` (`dialog` | `sheet`), `size` (`sm` | `md` | `lg` | `full`), `dismissOnBackdropPress`, `role`, `initialFocusRef`, `closeAccessibilityLabel`, `accessibilityLabel`, `testID`. Use it for every dialog instead of hand-building a header and an action row inside `Overlay`.
3599
3603
  - `RichText` — the formatted-content renderer. `<RichText value={post.body} />` parses the markdown subset (`**bold**`, `*italic*` / `_italic_`, `` `code` ``, `#`/`##`/`###` headings, `-`/`*` bullets, `1.` ordered items, one-line `![alt](src "large")` images) and renders it with SDK primitives, so formatted content reads the same in the web Player and the exported Expo app. `value` is markdown, NOT HTML — widgets have no `dangerouslySetInnerHTML` on either host, so tags in a content string render as literal tag soup; stored text that still holds legacy HTML is stripped to plain text rather than shown as markup. Props: `value`, `renderImage` (`({ src, alt, size }) => node` — supply it when images are filestore ids, because resolving one needs the scopes your own widget holds; without it only absolute `http(s)` URLs render), `style`, `testID`. Colour, type scale and leading come from the workspace theme — never re-style them.
3600
- - `MarkdownInput` — the authoring half of `<RichText>`. `<MarkdownInput value={draft} onChange={setDraft} />` is a rich-text field where the author edits the formatted result directly (headings, emphasis, code, links, lists and real tables), with a toolbar, a Table button and a Link button — the way to let an app USER write formatted text, instead of a bare `TextInput` plus hand-rolled buttons that can only splice literal tags into the value. The value stays markdown. Props: `value`, `onChange(next)`, `placeholder`, `pages` (offered by name in the Link form), `minHeight` (150) and `maxHeight` (280) — it grows between them, then scrolls — `accessibilityLabel`, `style`, `testID`. `showPreview`, `previewLabel` and `renderImage` are accepted and ignored.
3604
+ - `MarkdownInput` — the authoring half of `<RichText>`. `<MarkdownInput value={draft} onChange={setDraft} />` is a rich-text field where the author edits the formatted result directly (headings, emphasis, code, links, lists and real tables), with a toolbar, a Table button and a Link button — the way to let an app USER write formatted text, instead of a bare `TextInput` plus hand-rolled buttons that can only splice literal tags into the value. The value stays markdown. Props: `value`, `onChange(next)`, `placeholder`, `pages` (offered by name in the Link form), `minHeight` (150) and `maxHeight` (280) — it grows between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (filled with `{ insertText(text) }` to insert at the caret) and `editable` (`false` locks it, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are accepted and ignored.
3601
3605
  - `parseMarkdown`, `markdownToPlainText`, `parseMarkdownImage`, `formatMarkdownImage`, `stripHtmlToMarkdown`, `MARKDOWN_IMAGE_SIZES` — the same grammar as pure helpers, for content you inspect rather than render: the block list, a marker-free projection (list previews, search, a11y labels), the one-line image form read and written, a legacy-HTML row normalised to markdown on read, and the closed size list (`small` | `medium` | `large` | `full`).
3602
3606
  - `isSafeMarkdownImageSrc`, `isHttpImageSrc`, `normaliseMarkdownImageSize`, `readMarkdownAlt` — the image half of that grammar, for a widget rendering images itself via `renderImage`. `isSafeMarkdownImageSrc` is the same allowlist the parser applies (an `http(s)` URL or a filestore id; a `javascript:` scheme is refused), so the widget and the parser cannot disagree about which src is renderable.
3603
3607
  - `List`, `ListRow`, `ListHeader`, `EmptyState` — the themed list building blocks. `<ListRow title subtitle leading trailing onPress selected divider>` draws one record row from the theme's `list` scope (padding, height, gap, radius, background, divider); `<List>` spaces its rows and hands overrides down; `<ListHeader>` labels a table's columns on the rows' own inset; `<EmptyState icon title message>` is the "nothing here" panel. Use them by default for record rows and a table's header; build your own row when it needs what `ListRow` cannot do (a swipe-to-delete row, a row that expands in place).
package/dist/contract.cjs CHANGED
@@ -3746,7 +3746,7 @@ const PRIMITIVES = [
3746
3746
  {
3747
3747
  name: "MarkdownInput",
3748
3748
  description:
3749
- "Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`. `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
3749
+ "Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (a ref filled with `{ insertText(text) }`, which inserts plain text at the caret, e.g. from an emoji picker, or at the end before the user has placed one, and returns false while the editor loads), and `editable` (default true; `false` locks the field and its toolbar, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
3750
3750
  rnComponent: null,
3751
3751
  docsUrl: null,
3752
3752
  },
@@ -7027,7 +7027,10 @@ const CONTRACT = deepFreeze({
7027
7027
  // update writes a paid status is the `payment-status-written` warning.
7028
7028
  // 1.263.0: stricter lint — in a widget reading groupIds or useGroups(), a
7029
7029
  // propertySchema text field holding group ids is `group-ids-as-text`.
7030
- version: "1.263.0",
7030
+ // 1.264.0: additive (sc-17317) — `<MarkdownInput editorRef>` is filled
7031
+ // with `{ insertText(text) }`, inserting plain text at the caret, and
7032
+ // `editable={false}` locks the field and its toolbar.
7033
+ version: "1.264.0",
7031
7034
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7032
7035
  hooks: HOOKS,
7033
7036
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -3741,7 +3741,7 @@ const PRIMITIVES = [
3741
3741
  {
3742
3742
  name: "MarkdownInput",
3743
3743
  description:
3744
- "Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`. `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
3744
+ "Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (a ref filled with `{ insertText(text) }`, which inserts plain text at the caret, e.g. from an emoji picker, or at the end before the user has placed one, and returns false while the editor loads), and `editable` (default true; `false` locks the field and its toolbar, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
3745
3745
  rnComponent: null,
3746
3746
  docsUrl: null,
3747
3747
  },
@@ -7022,7 +7022,10 @@ const CONTRACT = deepFreeze({
7022
7022
  // update writes a paid status is the `payment-status-written` warning.
7023
7023
  // 1.263.0: stricter lint — in a widget reading groupIds or useGroups(), a
7024
7024
  // propertySchema text field holding group ids is `group-ids-as-text`.
7025
- version: "1.263.0",
7025
+ // 1.264.0: additive (sc-17317) — `<MarkdownInput editorRef>` is filled
7026
+ // with `{ insertText(text) }`, inserting plain text at the caret, and
7027
+ // `editable={false}` locks the field and its toolbar.
7028
+ version: "1.264.0",
7026
7029
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7027
7030
  hooks: HOOKS,
7028
7031
  primitives: PRIMITIVES,
package/dist/index.d.ts CHANGED
@@ -6216,8 +6216,23 @@ export const MarkdownInput: (props: {
6216
6216
  accessibilityLabel?: string;
6217
6217
  style?: any;
6218
6218
  testID?: string;
6219
+ /**
6220
+ * Filled with `{ insertText(text) }`, which inserts plain text at the caret
6221
+ * (e.g. from an emoji picker), or at the end before the user has placed one.
6222
+ * Returns false while the editor is loading; on iOS and Android true means
6223
+ * the text was sent to the editor page.
6224
+ */
6225
+ editorRef?:
6226
+ | { current: MarkdownInputHandle | null }
6227
+ | ((handle: MarkdownInputHandle | null) => void);
6228
+ /** False locks the field and its toolbar, e.g. while saving. Defaults to true. */
6229
+ editable?: boolean;
6219
6230
  }) => any;
6220
6231
 
6232
+ export interface MarkdownInputHandle {
6233
+ insertText(text: string): boolean;
6234
+ }
6235
+
6221
6236
  // ------------------------------------------------------- theme derivation
6222
6237
  // sc-3696: the colour maths both hosts resolve `useTheme()` with. Exported so
6223
6238
  // the Player (frontend/src/services/widgetTheme.js) and the exported app's
@@ -40,6 +40,7 @@ export function makeMarkdownEditorField({ View, WebView }) {
40
40
  tokens,
41
41
  minHeight,
42
42
  maxHeight,
43
+ editable = true,
43
44
  testID,
44
45
  },
45
46
  ref,
@@ -63,6 +64,10 @@ export function makeMarkdownEditorField({ View, WebView }) {
63
64
  send({ type: "set", markdown: value });
64
65
  }, [value, send]);
65
66
 
67
+ React.useEffect(() => {
68
+ send({ type: "editable", editable });
69
+ }, [editable, send]);
70
+
66
71
  // A theme switch repaints the page, as it does the web field.
67
72
  React.useEffect(() => {
68
73
  send({ type: "style", tokens, minHeight });
@@ -99,6 +104,7 @@ export function makeMarkdownEditorField({ View, WebView }) {
99
104
  label: accessibilityLabel,
100
105
  tokens,
101
106
  minHeight,
107
+ editable,
102
108
  });
103
109
  } else if (
104
110
  message.type === "change" &&
@@ -155,4 +155,4 @@ img.ProseMirror-separator {
155
155
  `);if(i.length<2)return;let s=i[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(s)||!s.includes("|"))return;let l=n1(o);if(l===o)return;let a=n.blockTokens(l)[0];if(a?.type!=="table"||!a.raw)return;let c=a.raw.split(`
156
156
  `).length,u=t.split(`
157
157
  `).slice(0,c).join(`
158
- `);return{...a,raw:u}}},addCommands(){return{insertTable:({rows:t=3,cols:e=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:o,editor:i})=>{let s=e1(i.schema,t,e,n);if(o){let l=r.selection.from+1;r.replaceSelectionWith(s).scrollIntoView().setSelection(v.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:t,dispatch:e})=>Af(t,e),addColumnAfter:()=>({state:t,dispatch:e})=>Tf(t,e),deleteColumn:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return Nf(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},addRowBefore:()=>({state:t,dispatch:e})=>Rf(t,e),addRowAfter:()=>({state:t,dispatch:e})=>Df(t,e),deleteRow:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return If(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},deleteTable:()=>({state:t,dispatch:e})=>zf(t,e),mergeCells:()=>({state:t,dispatch:e})=>bl(t,e),splitCell:()=>({state:t,dispatch:e})=>kl(t,e),toggleHeaderColumn:()=>({state:t,dispatch:e})=>wn("column")(t,e),toggleHeaderRow:()=>({state:t,dispatch:e})=>wn("row")(t,e),toggleHeaderCell:()=>({state:t,dispatch:e})=>Lf(t,e),mergeOrSplit:()=>({state:t,dispatch:e})=>bl(t,e)?!0:kl(t,e),setCellAttribute:(t,e)=>({state:n,dispatch:r})=>Pf(t,e)(n,r),goToNextCell:()=>({state:t,dispatch:e})=>wl(1)(t,e),goToPreviousCell:()=>({state:t,dispatch:e})=>wl(-1)(t,e),fixTables:()=>({state:t,dispatch:e})=>(e&&yl(t),!0),setCellSelection:t=>({tr:e,dispatch:n})=>{if(n){let r=j.create(e.doc,t.anchorCell,t.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Jo,"Mod-Backspace":Jo,Delete:Jo,"Mod-Delete":Jo}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Bf({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],Hf({allowTableNodeSelection:this.options.allowTableNodeSelection}),c1()]},addNodeView(){let t=this.options.View;return t?({node:e,view:n,HTMLAttributes:r})=>{let o=B(this.options.HTMLAttributes,r);return new t(e,this.options.cellMinWidth,n,o)}:null},extendNodeSchema(t){let e={name:t.name,options:t.options,storage:t.storage};return{tableRole:L(M(t,"tableRole",e))}}}),_S=W.create({name:"tableKit",addExtensions(){let t=[];return this.options.table!==!1&&t.push(Ml.configure(this.options.table)),this.options.tableCell!==!1&&t.push(xl.configure(this.options.tableCell)),this.options.tableHeader!==!1&&t.push(Cl.configure(this.options.tableHeader)),this.options.tableRow!==!1&&t.push(vl.configure(this.options.tableRow)),t}});function Xf(t={}){return new R({view(e){return new El(e,t)}})}var El=class{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let i=s=>{this[o](s)};return e.dom.addEventListener(o,i),{name:o,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){if(this.cursorPos!=null&&n.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,i=o.getBoundingClientRect(),s=i.width/o.offsetWidth,l=i.height/o.offsetHeight;if(n){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*s;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/s+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/s+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,i=typeof o=="function"?o(this.editorView,n,e):o;if(!n||i)return null;let s=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=wr(this.editorView.state.doc,s,this.editorView.dragging.slice);l!=null&&(s=l)}return s}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let n=this.computeTarget(e);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var ue=class t extends E{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return t.valid(r)?new t(r):E.near(r)}content(){return C.empty}eq(e){return e instanceof t&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new t(e.resolve(n.pos))}getBookmark(){return new Al(this.anchor)}static valid(e){let n=e.parent;if(n.inlineContent||!u1(e)||!d1(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&t.valid(e))return e;let o=e.pos,i=null;for(let s=e.depth;;s--){let l=e.node(s);if(n>0?e.indexAfter(s)<l.childCount:e.index(s)>0){i=l.child(n>0?e.indexAfter(s):e.index(s)-1);break}else if(s==0)return null;o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}for(;;){let s=n>0?i.firstChild:i.lastChild;if(!s){if(i.isAtom&&!i.isText&&!A.isSelectable(i)){e=e.doc.resolve(o+i.nodeSize*n),r=!1;continue e}break}i=s,o+=n;let l=e.doc.resolve(o);if(t.valid(l))return l}return null}}};ue.prototype.visible=!1;ue.findFrom=ue.findGapCursorFrom;E.jsonID("gapcursor",ue);var Al=class t{constructor(e){this.pos=e}map(e){return new t(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ue.valid(n)?new ue(n):E.near(n)}};function Yf(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function u1(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function d1(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Qf(){return new R({props:{decorations:m1,createSelectionBetween(t,e,n){return e.pos==n.pos&&ue.valid(n)?new ue(n):null},handleClick:h1,handleKeyDown:f1,handleDOMEvents:{beforeinput:p1}}})}var f1=_n({ArrowLeft:Go("horiz",-1),ArrowRight:Go("horiz",1),ArrowUp:Go("vert",-1),ArrowDown:Go("vert",1)});function Go(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,i){let s=r.selection,l=e>0?s.$to:s.$from,a=s.empty;if(s instanceof v){if(!i.endOfTextblock(n)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=ue.findGapCursorFrom(l,e,a);return c?(o&&o(r.tr.setSelection(new ue(c))),!0):!1}}function h1(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!ue.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&A.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ue(r))),!0)}function p1(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ue))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=b.empty;for(let s=r.length-1;s>=0;s--)o=b.from(r[s].createAndFill(null,o));let i=t.state.tr.replace(n.pos,n.pos,new C(o,0,0));return i.setSelection(v.near(i.doc.resolve(n.pos+1))),t.dispatch(i),!1}function m1(t){if(!(t.selection instanceof ue))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",$.create(t.doc,[Z.widget(t.selection.head,e,{key:"gapcursor"})])}var dx=W.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{let e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){let n=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(n)}return e.nodeSize},this.storage.words=t=>{let e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new R({key:new P("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;let o=this.options.limit,i=this.options.autoTrim;if(o==null||o===0||i===!1){t=!0;return}let s=this.storage.characters({node:r.doc});if(s>o){let l=s-o,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let o=this.storage.characters({node:n.doc}),i=this.storage.characters({node:e.doc});if(i<=r||o>r&&i>r&&i<=o)return!0;if(o>r&&i>r&&i>o||!e.getMeta("paste"))return!1;let s=e.selection.$head.pos,l=s-(i-r),a=s;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}}),fx=W.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Xf(this.options)]}}),hx=W.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new R({key:new P("focus"),props:{decorations:({doc:t,selection:e})=>{let{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return $.create(t,[]);let s=0;this.options.mode==="deepest"&&t.descendants((a,c)=>{if(!a.isText){if(!(o>=c&&o<=c+a.nodeSize-1))return!1;s+=1}});let l=0;return t.descendants((a,c)=>{if(a.isText||!(o>=c&&o<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&s-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(Z.node(c,c+a.nodeSize,{class:this.options.className}))}),$.create(t,i)}}})]}}),th=W.create({name:"gapCursor",addProseMirrorPlugins(){return[Qf()]},extendNodeSchema(t){var e;let n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=L(M(t,"allowGapCursor",n)))!==null&&e!==void 0?e:null}}}),nh="placeholder",Zf=new P("tiptap__placeholder");function rh(t){let{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=t,u=[a];return s&&u.push(c),Z.node(o,o+i.nodeSize,{class:u.join(" "),[r]:typeof n=="function"?n({editor:e,node:i,pos:o,hasAnchor:l}):n})}function oh(t,e){return typeof t=="function"?t(e):t}function ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){let{anchor:l}=o,a=[],c=t.isEmpty;return r.nodesBetween(i,s,(u,d)=>{let f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&hn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(rh({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function sh({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!(t.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:i}=o,s=[],l=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let a=r.resolve(i),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):i;if(c&&c.type.isTextblock&&hn(c)){let d=i>=u&&i<=u+c.nodeSize;s.push(rh({editor:t,isEmptyDoc:l,dataAttribute:n,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else s.push(...ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return $.create(r,s)}function ir(t,e){let n=t.resolve(e);if(n.depth===0){var r;let i=(r=n.nodeAfter)!==null&&r!==void 0?r:n.nodeBefore;if(!i)return{from:e,to:e};let s=n.nodeAfter?e:e-i.nodeSize;return{from:s,to:s+i.nodeSize}}let o=n.before(1);return{from:o,to:o+n.node(1).nodeSize}}function sr(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function g1(t,e,n){let r=[];return t.forEach((o,i)=>{let s=i,l=s+o.nodeSize,a=s+1,c=l+1;a<n&&c>e&&r.push({from:s,to:l})}),r}function y1(t){if(t.length===0)return[];let e=[...t].sort((r,o)=>r.from-o.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){let o=n[n.length-1],i=e[r];i.from<=o.to?o.to=Math.max(o.to,i.to):n.push({...i})}return n}function b1(t,e){let n=g1(t,e.from,e.to);return n.push(sr(t,ir(t,e.from))),e.to>e.from?n.push(sr(t,ir(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(sr(t,ir(t,Math.min(e.from+1,t.content.size)))),n}function k1(t,e,n){let r=[];if(t.docChanged){let o=fn(t);for(let i of o)r.push(...b1(n.doc,i.newRange))}return t.selectionSet&&(r.push(sr(n.doc,ir(n.doc,t.mapping.map(e.selection.anchor)))),r.push(sr(n.doc,ir(n.doc,n.selection.anchor)))),y1(r)}function w1(t,e,n){let r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function S1({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let l=t;for(let a of e){let{from:c,to:u}=w1(a.from,a.to,i),d=l.find(c,u).filter(h=>h.from>=c&&h.to<=u);d.length&&(l=l.remove(d));let f=ih({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:c,to:u});f.length&&(l=l.add(i,f))}return l}function x1({editor:t,options:e,dataAttribute:n}){return{init(r,o){let i=sh({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return i??$.empty},apply(r,o,i,s){return!r.docChanged&&!r.selectionSet?o:S1({decorations:o.map(r.mapping,r.doc),ranges:k1(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection})}}}function C1(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function v1({editor:t,options:e}){let n=e.dataAttribute?`data-${C1(e.dataAttribute)}`:`data-${nh}`,r=e.showOnlyCurrent&&!e.includeChildren;return new R({key:Zf,...r?{}:{state:x1({editor:t,options:e,dataAttribute:n})},props:{decorations:r?({doc:o,selection:i})=>sh({editor:t,options:e,dataAttribute:n,doc:o,selection:i}):o=>{var i;return e.showOnlyWhenEditable&&!t.isEditable?$.empty:(i=Zf.getState(o))!==null&&i!==void 0?i:$.empty}}})}var lh=W.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:nh,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[v1({editor:this.editor,options:this.options})]}});function Tl(t,e){return!t.selection.empty&&!Zu(t.selection)&&e.isEditable}function M1(t,e){return Tl(t,e)&&!e.isFocused&&!e.view.dragging}function E1(){var t;(t=window.getSelection())===null||t===void 0||t.removeAllRanges()}function A1(t){t.focus()}var px=W.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){let{editor:t,options:e}=this;return[new R({key:new P("selection"),props:{decorations(n){return M1(n,t)?$.create(n.doc,[Z.inline(n.selection.from,n.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(n){return Tl(n.state,t)&&E1(),!1},focus(n){return Tl(n.state,t)&&requestAnimationFrame(()=>{!t.isDestroyed&&n.hasFocus()&&A1(n)}),!1}}}})]}});function eh({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var ah=W.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;let e=new P(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)===null||t===void 0?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new R({key:e,appendTransaction:(o,i,s)=>{let{doc:l,tr:a,schema:c}=s,u=e.getState(s),d=l.content.size,f=c.nodes[n];if(!o.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(o,i)=>{let s=i.tr.doc.lastChild;return!eh({node:s,types:r})},apply:(o,i)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return i;let s=o.doc.lastChild;return!eh({node:s,types:r})}}})]}}),ch=W.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>hs(t,e),redo:()=>({state:t,dispatch:e})=>ps(t,e)}},addProseMirrorPlugins(){return[uu(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});import{markdownToDoc as uh,docToMarkdown as T1}from"./markdown-doc.js";import{isHttpImageSrc as N1}from"./markdown.js";var dh=/^\s*(javascript|data|vbscript):/i,O1=ff.extend({renderHTML({node:t,HTMLAttributes:e}){return N1(t.attrs.src)?["img",e]:["div",{class:"md-image-placeholder"},t.attrs.alt||"Image"]}}),R1=Ml.extend({addAttributes(){return{...this.parent?.(),align:{default:[],rendered:!1}}}}),Nl={content:"paragraph"};function D1(t){return[kd,wd,Sd,Md.extend({excludes:"italic code"}),Ed.extend({excludes:"bold code"}),Ad,Td.configure({levels:[1,2,3]}),Ps,Hs,$s.extend(Nl),Fs,uf.configure({openOnClick:!1,autolink:!1,isAllowedUri:e=>!dh.test(String(e)),HTMLAttributes:{target:null,rel:"noopener noreferrer nofollow"}}),df,O1.configure({inline:!1,allowBase64:!1}),R1.configure({resizable:!1}),vl,Cl.extend(Nl),xl.extend(Nl),th,ah,ch,lh.configure({placeholder:t||""})]}var fh={bold:t=>t.toggleBold(),italic:t=>t.toggleItalic(),code:t=>t.toggleCode(),heading2:t=>t.toggleHeading({level:2}),heading3:t=>t.toggleHeading({level:3}),bullet:t=>t.toggleBulletList(),ordered:t=>t.toggleOrderedList(),table:t=>t.insertTable({rows:3,cols:3,withHeaderRow:!0}),addRow:t=>t.addRowAfter(),addColumn:t=>t.addColumnAfter(),removeRow:t=>t.deleteRow(),removeColumn:t=>t.deleteColumn(),removeTable:t=>t.deleteTable(),undo:t=>t.undo(),redo:t=>t.redo(),link:(t,{label:e,target:n}={},r)=>{let o=String(n||"").trim();if(!o||dh.test(o))return t;let i=String(e||"").trim(),{from:s,to:l,empty:a}=r.state.selection;return!a&&(!i||i===r.state.doc.textBetween(s,l," ").trim())?t.setLink({href:o}):t.insertContent({type:"text",text:i||o,marks:[{type:"link",attrs:{href:o}}]})}},Dx=Object.freeze(Object.keys(fh));function Ix({element:t,markdown:e,placeholder:n,label:r,onChange:o,onFocusChange:i,onState:s}){let l=typeof e=="string"?e:"",a=new md({element:t,extensions:D1(n),content:uh(l,{stripLegacyHtml:!1}),editorProps:{attributes:{role:"textbox","aria-multiline":"true",...r?{"aria-label":r}:null}}});if(a.on("update",({transaction:c})=>{if(!c.docChanged)return;let u=T1(a.getJSON());u!==l&&(l=u,typeof o=="function"&&o(l))}),typeof s=="function"){let c=!1;a.on("transaction",()=>{let u=a.isActive("table");u!==c&&s({inTable:c=u})})}return typeof i=="function"&&(a.on("focus",()=>i(!0)),a.on("blur",()=>i(!1))),{setMarkdown(c){let u=typeof c=="string"?c:"";u!==l&&(l=u,a.commands.setContent(uh(u,{stripLegacyHtml:!1}),{emitUpdate:!1}))},command(c,u){let d=fh[c];return d?d(a.chain().focus(),u,a).run():!1},selectedText(){let{from:c,to:u}=a.state.selection;return a.state.doc.textBetween(c,u," ")},focus(){a.commands.focus()},destroy(){a.destroy()},editor:a}}export{Dx as MARKDOWN_EDITOR_COMMANDS,Ix as createMarkdownEditor};
158
+ `);return{...a,raw:u}}},addCommands(){return{insertTable:({rows:t=3,cols:e=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:o,editor:i})=>{let s=e1(i.schema,t,e,n);if(o){let l=r.selection.from+1;r.replaceSelectionWith(s).scrollIntoView().setSelection(v.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:t,dispatch:e})=>Af(t,e),addColumnAfter:()=>({state:t,dispatch:e})=>Tf(t,e),deleteColumn:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return Nf(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},addRowBefore:()=>({state:t,dispatch:e})=>Rf(t,e),addRowAfter:()=>({state:t,dispatch:e})=>Df(t,e),deleteRow:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return If(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},deleteTable:()=>({state:t,dispatch:e})=>zf(t,e),mergeCells:()=>({state:t,dispatch:e})=>bl(t,e),splitCell:()=>({state:t,dispatch:e})=>kl(t,e),toggleHeaderColumn:()=>({state:t,dispatch:e})=>wn("column")(t,e),toggleHeaderRow:()=>({state:t,dispatch:e})=>wn("row")(t,e),toggleHeaderCell:()=>({state:t,dispatch:e})=>Lf(t,e),mergeOrSplit:()=>({state:t,dispatch:e})=>bl(t,e)?!0:kl(t,e),setCellAttribute:(t,e)=>({state:n,dispatch:r})=>Pf(t,e)(n,r),goToNextCell:()=>({state:t,dispatch:e})=>wl(1)(t,e),goToPreviousCell:()=>({state:t,dispatch:e})=>wl(-1)(t,e),fixTables:()=>({state:t,dispatch:e})=>(e&&yl(t),!0),setCellSelection:t=>({tr:e,dispatch:n})=>{if(n){let r=j.create(e.doc,t.anchorCell,t.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Jo,"Mod-Backspace":Jo,Delete:Jo,"Mod-Delete":Jo}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Bf({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],Hf({allowTableNodeSelection:this.options.allowTableNodeSelection}),c1()]},addNodeView(){let t=this.options.View;return t?({node:e,view:n,HTMLAttributes:r})=>{let o=B(this.options.HTMLAttributes,r);return new t(e,this.options.cellMinWidth,n,o)}:null},extendNodeSchema(t){let e={name:t.name,options:t.options,storage:t.storage};return{tableRole:L(M(t,"tableRole",e))}}}),_S=W.create({name:"tableKit",addExtensions(){let t=[];return this.options.table!==!1&&t.push(Ml.configure(this.options.table)),this.options.tableCell!==!1&&t.push(xl.configure(this.options.tableCell)),this.options.tableHeader!==!1&&t.push(Cl.configure(this.options.tableHeader)),this.options.tableRow!==!1&&t.push(vl.configure(this.options.tableRow)),t}});function Xf(t={}){return new R({view(e){return new El(e,t)}})}var El=class{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let i=s=>{this[o](s)};return e.dom.addEventListener(o,i),{name:o,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){if(this.cursorPos!=null&&n.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,i=o.getBoundingClientRect(),s=i.width/o.offsetWidth,l=i.height/o.offsetHeight;if(n){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*s;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/s+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/s+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,i=typeof o=="function"?o(this.editorView,n,e):o;if(!n||i)return null;let s=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=wr(this.editorView.state.doc,s,this.editorView.dragging.slice);l!=null&&(s=l)}return s}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let n=this.computeTarget(e);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var ue=class t extends E{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return t.valid(r)?new t(r):E.near(r)}content(){return C.empty}eq(e){return e instanceof t&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new t(e.resolve(n.pos))}getBookmark(){return new Al(this.anchor)}static valid(e){let n=e.parent;if(n.inlineContent||!u1(e)||!d1(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&t.valid(e))return e;let o=e.pos,i=null;for(let s=e.depth;;s--){let l=e.node(s);if(n>0?e.indexAfter(s)<l.childCount:e.index(s)>0){i=l.child(n>0?e.indexAfter(s):e.index(s)-1);break}else if(s==0)return null;o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}for(;;){let s=n>0?i.firstChild:i.lastChild;if(!s){if(i.isAtom&&!i.isText&&!A.isSelectable(i)){e=e.doc.resolve(o+i.nodeSize*n),r=!1;continue e}break}i=s,o+=n;let l=e.doc.resolve(o);if(t.valid(l))return l}return null}}};ue.prototype.visible=!1;ue.findFrom=ue.findGapCursorFrom;E.jsonID("gapcursor",ue);var Al=class t{constructor(e){this.pos=e}map(e){return new t(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ue.valid(n)?new ue(n):E.near(n)}};function Yf(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function u1(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function d1(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Qf(){return new R({props:{decorations:m1,createSelectionBetween(t,e,n){return e.pos==n.pos&&ue.valid(n)?new ue(n):null},handleClick:h1,handleKeyDown:f1,handleDOMEvents:{beforeinput:p1}}})}var f1=_n({ArrowLeft:Go("horiz",-1),ArrowRight:Go("horiz",1),ArrowUp:Go("vert",-1),ArrowDown:Go("vert",1)});function Go(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,i){let s=r.selection,l=e>0?s.$to:s.$from,a=s.empty;if(s instanceof v){if(!i.endOfTextblock(n)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=ue.findGapCursorFrom(l,e,a);return c?(o&&o(r.tr.setSelection(new ue(c))),!0):!1}}function h1(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!ue.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&A.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ue(r))),!0)}function p1(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ue))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=b.empty;for(let s=r.length-1;s>=0;s--)o=b.from(r[s].createAndFill(null,o));let i=t.state.tr.replace(n.pos,n.pos,new C(o,0,0));return i.setSelection(v.near(i.doc.resolve(n.pos+1))),t.dispatch(i),!1}function m1(t){if(!(t.selection instanceof ue))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",$.create(t.doc,[Z.widget(t.selection.head,e,{key:"gapcursor"})])}var dx=W.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{let e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){let n=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(n)}return e.nodeSize},this.storage.words=t=>{let e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new R({key:new P("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;let o=this.options.limit,i=this.options.autoTrim;if(o==null||o===0||i===!1){t=!0;return}let s=this.storage.characters({node:r.doc});if(s>o){let l=s-o,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let o=this.storage.characters({node:n.doc}),i=this.storage.characters({node:e.doc});if(i<=r||o>r&&i>r&&i<=o)return!0;if(o>r&&i>r&&i>o||!e.getMeta("paste"))return!1;let s=e.selection.$head.pos,l=s-(i-r),a=s;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}}),fx=W.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Xf(this.options)]}}),hx=W.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new R({key:new P("focus"),props:{decorations:({doc:t,selection:e})=>{let{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return $.create(t,[]);let s=0;this.options.mode==="deepest"&&t.descendants((a,c)=>{if(!a.isText){if(!(o>=c&&o<=c+a.nodeSize-1))return!1;s+=1}});let l=0;return t.descendants((a,c)=>{if(a.isText||!(o>=c&&o<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&s-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(Z.node(c,c+a.nodeSize,{class:this.options.className}))}),$.create(t,i)}}})]}}),th=W.create({name:"gapCursor",addProseMirrorPlugins(){return[Qf()]},extendNodeSchema(t){var e;let n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=L(M(t,"allowGapCursor",n)))!==null&&e!==void 0?e:null}}}),nh="placeholder",Zf=new P("tiptap__placeholder");function rh(t){let{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=t,u=[a];return s&&u.push(c),Z.node(o,o+i.nodeSize,{class:u.join(" "),[r]:typeof n=="function"?n({editor:e,node:i,pos:o,hasAnchor:l}):n})}function oh(t,e){return typeof t=="function"?t(e):t}function ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){let{anchor:l}=o,a=[],c=t.isEmpty;return r.nodesBetween(i,s,(u,d)=>{let f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&hn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(rh({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function sh({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!(t.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:i}=o,s=[],l=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let a=r.resolve(i),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):i;if(c&&c.type.isTextblock&&hn(c)){let d=i>=u&&i<=u+c.nodeSize;s.push(rh({editor:t,isEmptyDoc:l,dataAttribute:n,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else s.push(...ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return $.create(r,s)}function ir(t,e){let n=t.resolve(e);if(n.depth===0){var r;let i=(r=n.nodeAfter)!==null&&r!==void 0?r:n.nodeBefore;if(!i)return{from:e,to:e};let s=n.nodeAfter?e:e-i.nodeSize;return{from:s,to:s+i.nodeSize}}let o=n.before(1);return{from:o,to:o+n.node(1).nodeSize}}function sr(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function g1(t,e,n){let r=[];return t.forEach((o,i)=>{let s=i,l=s+o.nodeSize,a=s+1,c=l+1;a<n&&c>e&&r.push({from:s,to:l})}),r}function y1(t){if(t.length===0)return[];let e=[...t].sort((r,o)=>r.from-o.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){let o=n[n.length-1],i=e[r];i.from<=o.to?o.to=Math.max(o.to,i.to):n.push({...i})}return n}function b1(t,e){let n=g1(t,e.from,e.to);return n.push(sr(t,ir(t,e.from))),e.to>e.from?n.push(sr(t,ir(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(sr(t,ir(t,Math.min(e.from+1,t.content.size)))),n}function k1(t,e,n){let r=[];if(t.docChanged){let o=fn(t);for(let i of o)r.push(...b1(n.doc,i.newRange))}return t.selectionSet&&(r.push(sr(n.doc,ir(n.doc,t.mapping.map(e.selection.anchor)))),r.push(sr(n.doc,ir(n.doc,n.selection.anchor)))),y1(r)}function w1(t,e,n){let r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function S1({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let l=t;for(let a of e){let{from:c,to:u}=w1(a.from,a.to,i),d=l.find(c,u).filter(h=>h.from>=c&&h.to<=u);d.length&&(l=l.remove(d));let f=ih({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:c,to:u});f.length&&(l=l.add(i,f))}return l}function x1({editor:t,options:e,dataAttribute:n}){return{init(r,o){let i=sh({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return i??$.empty},apply(r,o,i,s){return!r.docChanged&&!r.selectionSet?o:S1({decorations:o.map(r.mapping,r.doc),ranges:k1(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection})}}}function C1(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function v1({editor:t,options:e}){let n=e.dataAttribute?`data-${C1(e.dataAttribute)}`:`data-${nh}`,r=e.showOnlyCurrent&&!e.includeChildren;return new R({key:Zf,...r?{}:{state:x1({editor:t,options:e,dataAttribute:n})},props:{decorations:r?({doc:o,selection:i})=>sh({editor:t,options:e,dataAttribute:n,doc:o,selection:i}):o=>{var i;return e.showOnlyWhenEditable&&!t.isEditable?$.empty:(i=Zf.getState(o))!==null&&i!==void 0?i:$.empty}}})}var lh=W.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:nh,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[v1({editor:this.editor,options:this.options})]}});function Tl(t,e){return!t.selection.empty&&!Zu(t.selection)&&e.isEditable}function M1(t,e){return Tl(t,e)&&!e.isFocused&&!e.view.dragging}function E1(){var t;(t=window.getSelection())===null||t===void 0||t.removeAllRanges()}function A1(t){t.focus()}var px=W.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){let{editor:t,options:e}=this;return[new R({key:new P("selection"),props:{decorations(n){return M1(n,t)?$.create(n.doc,[Z.inline(n.selection.from,n.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(n){return Tl(n.state,t)&&E1(),!1},focus(n){return Tl(n.state,t)&&requestAnimationFrame(()=>{!t.isDestroyed&&n.hasFocus()&&A1(n)}),!1}}}})]}});function eh({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var ah=W.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;let e=new P(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)===null||t===void 0?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new R({key:e,appendTransaction:(o,i,s)=>{let{doc:l,tr:a,schema:c}=s,u=e.getState(s),d=l.content.size,f=c.nodes[n];if(!o.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(o,i)=>{let s=i.tr.doc.lastChild;return!eh({node:s,types:r})},apply:(o,i)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return i;let s=o.doc.lastChild;return!eh({node:s,types:r})}}})]}}),ch=W.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>hs(t,e),redo:()=>({state:t,dispatch:e})=>ps(t,e)}},addProseMirrorPlugins(){return[uu(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});import{markdownToDoc as uh,docToMarkdown as T1}from"./markdown-doc.js";import{isHttpImageSrc as N1}from"./markdown.js";var dh=/^\s*(javascript|data|vbscript):/i,O1=ff.extend({renderHTML({node:t,HTMLAttributes:e}){return N1(t.attrs.src)?["img",e]:["div",{class:"md-image-placeholder"},t.attrs.alt||"Image"]}}),R1=Ml.extend({addAttributes(){return{...this.parent?.(),align:{default:[],rendered:!1}}}}),Nl={content:"paragraph"};function D1(t){return[kd,wd,Sd,Md.extend({excludes:"italic code"}),Ed.extend({excludes:"bold code"}),Ad,Td.configure({levels:[1,2,3]}),Ps,Hs,$s.extend(Nl),Fs,uf.configure({openOnClick:!1,autolink:!1,isAllowedUri:e=>!dh.test(String(e)),HTMLAttributes:{target:null,rel:"noopener noreferrer nofollow"}}),df,O1.configure({inline:!1,allowBase64:!1}),R1.configure({resizable:!1}),vl,Cl.extend(Nl),xl.extend(Nl),th,ah,ch,lh.configure({placeholder:t||""})]}var fh={bold:t=>t.toggleBold(),italic:t=>t.toggleItalic(),code:t=>t.toggleCode(),heading2:t=>t.toggleHeading({level:2}),heading3:t=>t.toggleHeading({level:3}),bullet:t=>t.toggleBulletList(),ordered:t=>t.toggleOrderedList(),table:t=>t.insertTable({rows:3,cols:3,withHeaderRow:!0}),addRow:t=>t.addRowAfter(),addColumn:t=>t.addColumnAfter(),removeRow:t=>t.deleteRow(),removeColumn:t=>t.deleteColumn(),removeTable:t=>t.deleteTable(),insertText:(t,{text:e}={})=>typeof e=="string"&&e?t.insertContent({type:"text",text:e}):t,undo:t=>t.undo(),redo:t=>t.redo(),link:(t,{label:e,target:n}={},r)=>{let o=String(n||"").trim();if(!o||dh.test(o))return t;let i=String(e||"").trim(),{from:s,to:l,empty:a}=r.state.selection;return!a&&(!i||i===r.state.doc.textBetween(s,l," ").trim())?t.setLink({href:o}):t.insertContent({type:"text",text:i||o,marks:[{type:"link",attrs:{href:o}}]})}},Dx=Object.freeze(Object.keys(fh));function Ix({element:t,markdown:e,placeholder:n,label:r,onChange:o,onFocusChange:i,onState:s}){let l=typeof e=="string"?e:"",a=new md({element:t,extensions:D1(n),content:uh(l,{stripLegacyHtml:!1}),editorProps:{attributes:{role:"textbox","aria-multiline":"true",...r?{"aria-label":r}:null}}});if(a.on("update",({transaction:u})=>{if(!u.docChanged)return;let d=T1(a.getJSON());d!==l&&(l=d,typeof o=="function"&&o(l))}),typeof s=="function"){let u=!1;a.on("transaction",()=>{let d=a.isActive("table");d!==u&&s({inTable:u=d})})}let c=!1;return a.on("transaction",({transaction:u})=>{u.selectionSet&&(c=!0)}),typeof i=="function"&&(a.on("focus",()=>i(!0)),a.on("blur",()=>i(!1))),{setMarkdown(u){let d=typeof u=="string"?u:"";d!==l&&(l=d,a.commands.setContent(uh(d,{stripLegacyHtml:!1}),{emitUpdate:!1}))},command(u,d){let f=fh[u];if(!f)return!1;let h=u==="insertText"&&!c?"end":null;return f(a.chain().focus(h),d,a).run()},selectedText(){let{from:u,to:d}=a.state.selection;return a.state.doc.textBetween(u,d," ")},focus(){a.commands.focus()},setEditable(u){a.setEditable(u!==!1)},destroy(){a.destroy()},editor:a}}export{Dx as MARKDOWN_EDITOR_COMMANDS,Ix as createMarkdownEditor};
@@ -89,6 +89,9 @@ const COMMANDS = {
89
89
  removeRow: (chain) => chain.deleteRow(),
90
90
  removeColumn: (chain) => chain.deleteColumn(),
91
91
  removeTable: (chain) => chain.deleteTable(),
92
+ // A text node, never a parsed string, so inserted text cannot become markup.
93
+ insertText: (chain, { text } = {}) =>
94
+ typeof text === "string" && text ? chain.insertContent({ type: "text", text }) : chain,
92
95
  undo: (chain) => chain.undo(),
93
96
  redo: (chain) => chain.redo(),
94
97
  link: (chain, { label, target } = {}, editor) => {
@@ -151,6 +154,12 @@ export function createMarkdownEditor({
151
154
  if (next !== inTable) onState({ inTable: (inTable = next) });
152
155
  });
153
156
  }
157
+ // Until the author places a caret, an insert appends rather than prepends.
158
+ // Loading a value never sets a selection; a click or select-all does.
159
+ let caretPlaced = false;
160
+ editor.on("transaction", ({ transaction }) => {
161
+ if (transaction.selectionSet) caretPlaced = true;
162
+ });
154
163
  if (typeof onFocusChange === "function") {
155
164
  editor.on("focus", () => onFocusChange(true));
156
165
  editor.on("blur", () => onFocusChange(false));
@@ -167,7 +176,8 @@ export function createMarkdownEditor({
167
176
  command(name, args) {
168
177
  const build = COMMANDS[name];
169
178
  if (!build) return false;
170
- return build(editor.chain().focus(), args, editor).run();
179
+ const at = name === "insertText" && !caretPlaced ? "end" : null;
180
+ return build(editor.chain().focus(at), args, editor).run();
171
181
  },
172
182
  selectedText() {
173
183
  const { from, to } = editor.state.selection;
@@ -176,6 +186,9 @@ export function createMarkdownEditor({
176
186
  focus() {
177
187
  editor.commands.focus();
178
188
  },
189
+ setEditable(editable) {
190
+ editor.setEditable(editable !== false);
191
+ },
179
192
  destroy() {
180
193
  editor.destroy();
181
194
  },
@@ -22,13 +22,13 @@ function touchFontSize(size) {
22
22
  }
23
23
 
24
24
  export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField(
25
- { value, onChangeText, onStateChange, placeholder, accessibilityLabel, tokens, minHeight, maxHeight, testID },
25
+ { value, onChangeText, onStateChange, placeholder, accessibilityLabel, tokens, minHeight, maxHeight, editable = true, testID },
26
26
  ref,
27
27
  ) {
28
28
  const host = React.useRef(null);
29
29
  const editor = React.useRef(null);
30
- const latest = React.useRef({ value, onChangeText, onStateChange });
31
- latest.current = { value, onChangeText, onStateChange };
30
+ const latest = React.useRef({ value, onChangeText, onStateChange, editable });
31
+ latest.current = { value, onChangeText, onStateChange, editable };
32
32
  const [failed, setFailed] = React.useState(false);
33
33
  const scope = `md-editor-${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
34
34
 
@@ -53,6 +53,7 @@ export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField
53
53
  });
54
54
  // The parent may have replaced the value while the editor loaded.
55
55
  editor.current.setMarkdown(latest.current.value);
56
+ editor.current.setEditable(latest.current.editable);
56
57
  })
57
58
  .catch(() => {
58
59
  if (!cancelled) setFailed(true);
@@ -70,6 +71,10 @@ export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField
70
71
  if (editor.current) editor.current.setMarkdown(value);
71
72
  }, [value]);
72
73
 
74
+ React.useEffect(() => {
75
+ if (editor.current) editor.current.setEditable(editable);
76
+ }, [editable]);
77
+
73
78
  React.useImperativeHandle(
74
79
  ref,
75
80
  () => ({